<!doctype html>




<html class="theme-next mist" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="XKshOK3-ivpL8NoZ-P3JABgVNXF9cwGXb0Uc1TWc0X0" />













  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java,JNI,so,jnilib," />





  <link rel="alternate" href="/feed.xml" title="Wander's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="&amp;emsp;&amp;emsp;本文用的是 JDK 1.7 版本，使用 Ubuntu 14.04.2 LTS 编译 so，macOS Sierra 10.12.4 编译 jnilib。主要步骤就如下三步，具体代码见 https://github.com/wanderhero/test-normal-project.git：&amp;emsp;&amp;emsp;1.加载实现了 native 函数的动态库；&amp;emsp;&amp;e">
<meta name="keywords" content="Java,JNI,so,jnilib">
<meta property="og:type" content="article">
<meta property="og:title" content="Java 通过 JNI 调用 so/jnilib 动态链接库">
<meta property="og:url" content="http://0613.me/2017/05/14/20170514 - Java-通过-JNI-调用-so-jnilib-动态链接库/index.html">
<meta property="og:site_name" content="Wander's Blog">
<meta property="og:description" content="&amp;emsp;&amp;emsp;本文用的是 JDK 1.7 版本，使用 Ubuntu 14.04.2 LTS 编译 so，macOS Sierra 10.12.4 编译 jnilib。主要步骤就如下三步，具体代码见 https://github.com/wanderhero/test-normal-project.git：&amp;emsp;&amp;emsp;1.加载实现了 native 函数的动态库；&amp;emsp;&amp;e">
<meta property="og:image" content="http://wander.u.qiniudn.com/20170514-1632-0.0.jpg?imageView2/2/h/140/imageslim">
<meta property="og:image" content="http://wander.u.qiniudn.com/20170514-1632-0.1.jpg?imageView2/2/h/140/imageslim">
<meta property="og:updated_time" content="2017-05-15T10:05:50.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java 通过 JNI 调用 so/jnilib 动态链接库">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;本文用的是 JDK 1.7 版本，使用 Ubuntu 14.04.2 LTS 编译 so，macOS Sierra 10.12.4 编译 jnilib。主要步骤就如下三步，具体代码见 https://github.com/wanderhero/test-normal-project.git：&amp;emsp;&amp;emsp;1.加载实现了 native 函数的动态库；&amp;emsp;&amp;e">
<meta name="twitter:image" content="http://wander.u.qiniudn.com/20170514-1632-0.0.jpg?imageView2/2/h/140/imageslim">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'L34XZDY661',
      apiKey: 'e2f02dacf5ff8155a9f9390f100de654',
      indexName: '42bf5dc7558a177308743da34255dbd4',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于 ${query} 的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://0613.me/2017/05/14/20170514 - Java-通过-JNI-调用-so-jnilib-动态链接库/"/>





  <title> Java 通过 JNI 调用 so/jnilib 动态链接库 | Wander's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98124780-1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c098f92aa7d6d02d9d76535b3f55b30c";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61887471";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



<script>
  	var _mtac = {};
  	(function() {
  		var mta = document.createElement("script");
  		mta.src = "http://pingjs.qq.com/h5/stats.js?v2.0.2";
  		mta.setAttribute("name", "MTAH5");
  		mta.setAttribute("sid", "500442890");

  		var s = document.getElementsByTagName("script")[0];
  		s.parentNode.insertBefore(mta, s);
  	})();
</script>



  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261814436&web_id=1261814436" language="JavaScript"></script>
  </div>






  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Wander's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">温故而知新</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://0613.me/2017/05/14/20170514 - Java-通过-JNI-调用-so-jnilib-动态链接库/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Wander.Zeng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://wander.u.qiniudn.com/avatar.png?imageslim">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wander's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">
            
            
              
                Java 通过 JNI 调用 so/jnilib 动态链接库
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-14T16:32:56+08:00">
                2017-05-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/JNI/" itemprop="url" rel="index">
                    <span itemprop="name">JNI</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2017/05/14/20170514 - Java-通过-JNI-调用-so-jnilib-动态链接库/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2017/05/14/20170514 - Java-通过-JNI-调用-so-jnilib-动态链接库/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2017/05/14/20170514 - Java-通过-JNI-调用-so-jnilib-动态链接库/" class="leancloud_visitors" data-flag-title="Java 通过 JNI 调用 so/jnilib 动态链接库">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>&emsp;&emsp;本文用的是 <strong>JDK 1.7</strong> 版本，使用 <strong>Ubuntu 14.04.2 LTS</strong> 编译 so，<strong>macOS Sierra 10.12.4</strong> 编译 jnilib。<br>主要步骤就如下三步，具体代码见 <a href="https://github.com/wanderhero/test-normal-project" target="_blank" rel="external"><strong>https://github.com/wanderhero/test-normal-project.git</strong></a>：<br>&emsp;&emsp;1.加载实现了 native 函数的动态库；<br>&emsp;&emsp;2.声明 native 函数；<br>&emsp;&emsp;3.调用 native 函数。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">package com.wander.jni;</div><div class="line"></div><div class="line">public class JNITest &#123;</div><div class="line">	static &#123;</div><div class="line">		System.loadLibrary(<span class="string">"JNITest"</span>);// 加载实现了native函数的动态库</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	public static native String <span class="built_in">test</span>(String name);// 声明native函数</div><div class="line"></div><div class="line">	public static void main(String[] args) &#123;</div><div class="line">		System.out.println(<span class="built_in">test</span>(<span class="string">"wander"</span>));// 调用 native 函数</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<a id="more"></a>
<hr>
<h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>&emsp;&emsp;其实 Java 方面不是大问题，关键问题在于如何生成 动态链接库。首先还是先了解下什么是 JNI，才能知己知彼，百战不殆。<br>&emsp;&emsp;参考自 <a href="#参考1"><strong>xyang0917</strong></a>，JNI 全称是 Java Native Interface (Java本地接口) 单词首字母的缩写，本地接口就是指用 C 和 C++ 开发的接口。由于 JNI 是 JVM 规范中的一部份，因此可以将我们写的 JNI 程序在任何实现了 JNI 规范的 Java 虚拟机中运行。同时，这个特性使我们可以复用以前用 C/C++ 写的大量代码。<br>&emsp;&emsp;开发 JNI 程序会受到系统环境的限制，因为用 C/C++ 语言写出来的代码或模块，编译过程当中要依赖当前操作系统环境所提供的一些库函数，并和本地库链接在一起。而且编译后生成的二进制代码只能在本地操作系统环境下运行，因为不同的操作系统环境，有自己的本地库和 CPU 指令集，而且各个平台对标准 C/C++ 的规范和标准库函数实现方式也有所区别。这就造成使用了 JNI 接口的 JAVA 程序，不再像以前那样自由的跨平台。如果要实现跨平台，就必须将本地代码在不同的操作系统平台下编译出相应的动态库(<strong>windows：#.dll, linux/unix：lib#.so, mac os x：lib#.jnilib</strong>)。  </p>
<h3 id="生成-C-C-代码"><a href="#生成-C-C-代码" class="headerlink" title="生成 C/C++ 代码"></a>生成 C/C++ 代码</h3><p>&emsp;&emsp;如果已有 C/C++ 文件，可跳过此步。<br>&emsp;&emsp;最开始我们已经新建了一个 <strong>JNITest.java</strong> 源文件，那就基于此文件快速生成 .h 头文件。  </p>
<ul>
<li><strong>首先获取 .class 字节码文件，如果没有生成，可以通过 javac 命令将 .java 源文件编译而成。</strong><br>注意是在工程根目录下，-d 表示将编译后的 class 文件放到指定的目录下，这里我把它放到和 src 同级的 bin 目录下。</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">192:<span class="built_in">test</span>-normal-project wander$ javac src/com/wander/jni/JNITest.java <span class="_">-d</span> ./bin</div></pre></td></tr></table></figure>
<ul>
<li><strong>然后就可以用 javah -jni 命令，根据 class 字节码文件生成 .h 头文件。</strong><br>默认生成的 .h 头文件名为 com_wander_jni_JNITest.h（包名+类名.h），我把它放在和 src 同级的 res/jni 目录下。    </li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ javah -jni -classpath ./bin <span class="_">-d</span> ./res/jni com.wander.jni.JNITest</div></pre></td></tr></table></figure>
<p>&emsp;&emsp;&emsp;也可以通过 -o 参数指定生成头文件名称，注意不能和 -d 混用，默认生成到同级目录下。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ javah -jni -classpath ./bin -o JNITest.h com.wander.jni.JNITest</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;&emsp;参数说明，注意：-d 和 -o 只能使用其中一个参数，具体查看 <strong>javah -help</strong>：<br>&emsp;&emsp;&emsp;&emsp;-classpath ：类搜索路径，这里表示从当前的 bin 目录下查找<br>&emsp;&emsp;&emsp;&emsp;-d ：将生成的头文件放到当前的 res/jni 目录下<br>&emsp;&emsp;&emsp;&emsp;-o ：指定生成的头文件名称  </p>
<p>&emsp;&emsp;&emsp;生成的 .h 头文件如下：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line">/* DO NOT EDIT THIS FILE - it is machine generated */</div><div class="line"><span class="comment">#include &lt;jni.h&gt;</span></div><div class="line">/* Header <span class="keyword">for</span> class com_wander_jni_JNITest */</div><div class="line"></div><div class="line"><span class="comment">#ifndef _Included_com_wander_jni_JNITest</span></div><div class="line"><span class="comment">#define _Included_com_wander_jni_JNITest</span></div><div class="line"><span class="comment">#ifdef __cplusplus</span></div><div class="line">extern <span class="string">"C"</span> &#123;</div><div class="line"><span class="comment">#endif</span></div><div class="line">/*</div><div class="line"> * Class:     com_wander_jni_JNITest</div><div class="line"> * Method:    <span class="built_in">test</span></div><div class="line"> * Signature: (Ljava/lang/String;)Ljava/lang/String;</div><div class="line"> */</div><div class="line">JNIEXPORT jstring JNICALL Java_com_wander_jni_JNITest_test</div><div class="line">  (JNIEnv *, jclass, jstring);</div><div class="line"></div><div class="line"><span class="comment">#ifdef __cplusplus</span></div><div class="line">&#125;</div><div class="line"><span class="comment">#endif</span></div><div class="line"><span class="comment">#endif</span></div></pre></td></tr></table></figure></p>
<ul>
<li><strong>最后根据 .h头文件生成 .c 文件</strong><br>此处我在 c 里面打印 <strong>Hello ${name}</strong>，同时返回 <strong>return ${name}</strong></li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line">// com_wander_jni_JNITest.c  </div><div class="line">  </div><div class="line"><span class="comment">#include "com_wander_jni_JNITest.h"  </span></div><div class="line">  </div><div class="line"><span class="comment">#ifdef __cplusplus  </span></div><div class="line">extern <span class="string">"C"</span>  </div><div class="line">&#123;  </div><div class="line"><span class="comment">#endif   </span></div><div class="line">/*</div><div class="line"> * Class:     com_wander_jni_JNITest</div><div class="line"> * Method:    <span class="built_in">test</span></div><div class="line"> * Signature: (Ljava/lang/String;)Ljava/lang/String;</div><div class="line"> */</div><div class="line">JNIEXPORT jstring JNICALL Java_com_wander_jni_JNITest_test(  </div><div class="line">        JNIEnv *env, jclass cls, jstring j_str) </div><div class="line">&#123;  </div><div class="line">    const char *c_str = NULL;  </div><div class="line">    char buff[128] = &#123; 0 &#125;;  </div><div class="line">    c_str = (*env)-&gt;GetStringUTFChars(env, j_str, NULL);  </div><div class="line">    <span class="keyword">if</span> (c_str == NULL)  </div><div class="line">    &#123;  </div><div class="line">        <span class="built_in">printf</span>(<span class="string">"out of memory.\n"</span>);  </div><div class="line">        <span class="built_in">return</span> NULL;  </div><div class="line">    &#125;  </div><div class="line">    <span class="built_in">printf</span>(<span class="string">"Hello %s in c\n"</span>, c_str);  </div><div class="line">    sprintf(buff, <span class="string">"return %s"</span>, c_str);  </div><div class="line">    (*env)-&gt;ReleaseStringUTFChars(env, j_str, c_str);  </div><div class="line">    <span class="built_in">return</span> (*env)-&gt;NewStringUTF(env, buff);  </div><div class="line">&#125;  </div><div class="line"><span class="comment">#ifdef __cplusplus  </span></div><div class="line">&#125;  </div><div class="line"><span class="comment">#endif</span></div></pre></td></tr></table></figure>
<h3 id="将-C-C-代码编译成动态库文件"><a href="#将-C-C-代码编译成动态库文件" class="headerlink" title="将 C/C++ 代码编译成动态库文件"></a>将 C/C++ 代码编译成动态库文件</h3><p>&emsp;&emsp;最近爆发了 比特币勒索病毒，三个操作系统的优劣好差估计又有谈资了。</p>
<ul>
<li><strong>Linux/Unix</strong><br>参数说明：<br>&emsp;-I：包含编译JNI必要的头文件<br>&emsp;-fPIC：编译成与位置无关的独立代码<br>&emsp;-shared：编译成动态库<br>&emsp;-o：指定编译后动态库生成的路径和文件名<br>本文用的是 阿里云 的 Ubuntu 14.04.2 LTS，把 .h 和 .c 文件放到同一目录下，通过 gcc 命令一步生成 libJNITest.so。</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ gcc -I<span class="variable">$JAVA_HOME</span>/include -I<span class="variable">$JAVA_HOME</span>/include/linux <span class="_">-f</span>PIC -shared com_wander_jni_JNITest.c -o libJNITest.so</div></pre></td></tr></table></figure>
<ul>
<li><strong>Mac OS X</strong><br>参数说明：<br>&emsp;-dynamiclib：表示编译成动态链接库<br>&emsp;-o：指定动态链接库编译后生成的路径及文件名<br>&emsp;-framework JavaVM -I：编译JNI需要用到JVM的头文件(jni.h)，第一个目录是平台无关的，第二个目录是与操作系统平台相关的头文件</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ gcc -dynamiclib -o libJNITest.jnilib com_wander_jni_JNITest.c -framework JavaVM -I/<span class="variable">$JAVA_HOME</span>/include -I/<span class="variable">$JAVA_HOME</span>/include/darwin</div></pre></td></tr></table></figure>
<p>&emsp;&emsp;&emsp;看上去也很简单，但是在我的电脑上却报错了，提示 <strong>‘jni.h’ file not found(找不到 jni 头文件)</strong>，感谢 <a href="#参考2"><strong>Stack Overflow</strong></a>，找到了貌似正确的命令，却提示 <strong>Operation not permitted(不允许操作)</strong>，加了 sudo 都不行，难道我的人品差到连系统都不忍直视了吗？事实证明，人品是挺差的，但功夫不负有心人，感谢 <a href="#参考3"><strong>小胡子哥</strong></a>，原来 Apple 在 OS X 10.11 以后的版本中默认启动了一项系统保护程序，叫做 System Integrity Protection，也被唤作 rootless（寓意让 root 弱一点），该程序意在保护电脑不被恶意程序攻击，感觉屌屌的，以安全的名义，一切都是可以接受的。<br>&emsp;&emsp;&emsp;SIP 会锁定几个系统文件目录：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">/System</div><div class="line">/sbin</div><div class="line">/usr （/usr/<span class="built_in">local</span> 除外）</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;&emsp;在 SIP 的保护下，部分软件、功能、脚本都会失效，还好 mac 提供了命令，我们可以通过 csrutil 来检测系统当前 SIP 的启动状态、打开或关闭此功能。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">$ csrutil status</div><div class="line">System Integrity Protection status: enabled.</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;&emsp;enabled 说明当前我的系统是在 SIP 保护下的，我们可以通过如下步骤关闭 SIP，以防万一，可以先做个 Time Machine 备份：<br>&emsp;&emsp;&emsp;&emsp;- 重启电脑，按下 Command + R 直到听到开机声音，此时电脑会进入恢复模式（Recovery Mode）<br>&emsp;&emsp;&emsp;&emsp;- 当 macOS 实用工具出现在屏幕中时，选择 实用工具(Utilities) 菜单，选择 终端(Terminal)<br>&emsp;&emsp;&emsp;&emsp;- 输入 csrutil disable，回车<br>&emsp;&emsp;&emsp;&emsp;- 电脑重启后，SIP 就关闭了<br>&emsp;&emsp;&emsp;恢复 SIP 的方式同上，只不过终端中输入 csrutil enable 即可。</p>
<p><div style="float: left"><a href="http://wander.u.qiniudn.com/20170514-1632-0.0.jpg?imageslim" target="_blank" rel="external"><img src="http://wander.u.qiniudn.com/20170514-1632-0.0.jpg?imageView2/2/h/140/imageslim" alt=""></a></div><a href="http://wander.u.qiniudn.com/20170514-1632-0.1.jpg?imageslim" target="_blank" rel="external"><img src="http://wander.u.qiniudn.com/20170514-1632-0.1.jpg?imageView2/2/h/140/imageslim" alt=""></a>    </p>
<p>&emsp;&emsp;&emsp;关闭了 SIP 后，再来试试之前的 jni 头文件找不到的问题，果然 OK，这里我采用的是 jdk1.7 版本：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">$ <span class="built_in">cd</span> /System/Library/Frameworks/JavaVM.framework/Versions</div><div class="line">$ sudo ln -nsf /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents ./CurrentJDK</div><div class="line"></div><div class="line">$ <span class="built_in">cd</span> /System/Library/Frameworks/JavaVM.framework</div><div class="line">$ sudo ln -nsf Versions/CurrentJDK/Home/include/ ./Headers</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;&emsp;问题扫除后，再执行 gcc 命令，libJNITest.jnilib 顺利生成~</p>
<ul>
<li><strong>Windows</strong><br>由于手上没有 Windows 电脑，Windows 的验证暂缺。</li>
</ul>
<h3 id="运行-Java-程序"><a href="#运行-Java-程序" class="headerlink" title="运行 Java 程序"></a>运行 Java 程序</h3><p>&emsp;&emsp;经过了漫长的准备，动态链接库 终于到手，接下来就差最后一把火了。此时如果心急直接运行，程序会毫不留情地抛给你一个 java.lang.UnsatisfiedLinkError 异常，且无法 try catch。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">Exception <span class="keyword">in</span> thread <span class="string">"main"</span> java.lang.UnsatisfiedLinkError: no JNITest1 <span class="keyword">in</span> java.library.path</div><div class="line">	at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886)</div><div class="line">	at java.lang.Runtime.loadLibrary0(Runtime.java:849)</div><div class="line">	at java.lang.System.loadLibrary(System.java:1088)</div><div class="line">	at com.wander.jni.JNITest.&lt;clinit&gt;(JNITest.java:5)</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;一般在类的静态 (static) 代码块中加载动态库最合适，因为在创建类的实例时，类会被 ClassLoader 先加载到虚拟机，随后立马调用类的 static 静态代码块。这时再去调用 native 方法就万无一失了。加载动态库的两种方式：<br>&emsp;&emsp;方法1简单粗暴，指定要调用的动态链接库的绝对路径即可，只是在跨平台访问时，需要指定对应平台的文件路径，且不同平台文件的前缀和后缀都不一样；<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">System.load(<span class="string">"/Users/wander/MyDocuments/workspace/workspace4eclipse/test-normal-project/res/jni/libJNITest.jnilib"</span>);</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;方法2只需要指定动态库的名字即可，不需要前缀后缀，java 会去 java.library.path 系统属性指定的目录下查找动态库文件，一劳永逸；<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">System.loadLibrary(<span class="string">"JNITest"</span>);</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;这里我写了一个简单类去查看 java.library.path 路径，和环境变量一样，每个路径用:分割，随便放到哪个路径下都有效。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">package com.wander.jni;</div><div class="line"></div><div class="line">public class JavaLibraryPath &#123;</div><div class="line">	public static void main(String[] args) &#123;</div><div class="line">		System.out.println(System.getProperty(<span class="string">"java.library.path"</span>));</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;做成可执行 Jar 文件，就可以在多平台上运行查看了。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">$ java -jar JavaLibraryPath.jar</div><div class="line">/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;如此这般，就可以再做个可执行 Jar 文件，在 linux/unix 平台上访问了，mac 系统更是可以在 IDE 里面运行调试了。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$ java -jar JNITest.jar </div><div class="line">Hello wander <span class="keyword">in</span> c</div><div class="line"><span class="built_in">return</span> wander</div></pre></td></tr></table></figure></p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>&emsp;&emsp;不会 C/C++ 的 Java 程序员也可以用好 JNI~</p>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><ul>
<li><span id="参考1"><a href="http://blog.csdn.net/xyang81/article/details/41777471" target="_blank" rel="external">JNI/NDK开发指南（一）—— JNI开发流程及HelloWorld</a></span>  </li>
<li><span id="参考2"><a href="http://stackoverflow.com/questions/9704376/how-to-install-java-native-development-headers-on-os-x-lion" target="_blank" rel="external">Stack Overflow - How to install Java native development headers on OS X Lion</a></span> </li>
<li><span id="参考3"><a href="http://www.barretlee.com/blog/2016/04/06/operation-not-permitted-problem-in-linux-or-unix-system/" target="_blank" rel="external">小胡子哥的个人博客 - Unix/Linux 系统中的 Operation Not Permitted 问题</a></span> </li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持是我创作的动力！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="http://wander.u.qiniudn.com/ali_pay.png?imageslim" alt="Wander.Zeng Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="http://wander.u.qiniudn.com/wechatpay.png?imageslim" alt="Wander.Zeng WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        
  <ul class="post-copyright">
    <!--
    <li class="post-copyright-author">
      <strong>本文作者：</strong>
      Wander.Zeng
    </li>
    -->
    <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://0613.me/2017/05/14/20170514 - Java-通过-JNI-调用-so-jnilib-动态链接库/" title="Java 通过 JNI 调用 so/jnilib 动态链接库">http://0613.me/2017/05/14/20170514 - Java-通过-JNI-调用-so-jnilib-动态链接库/</a>
    </li>
    <!--
    <li class="post-copyright-license">
      <strong>版权声明： </strong>
      本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
    </li>
    -->
  </ul>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag"># Java</a>
          
            <a href="/tags/JNI/" rel="tag"># JNI</a>
          
            <a href="/tags/so/" rel="tag"># so</a>
          
            <a href="/tags/jnilib/" rel="tag"># jnilib</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/05/19/20170519 - 通过-Java-实现-pcm-格式-转-wav-格式并分别通过-Swing-和-Web-的形式绘制波形图/" rel="next" title="使用 Java 实现 PCM 格式 转 WAV 格式并分别通过 Swing 和 Web 的形式绘制波形图">
                <i class="fa fa-chevron-left"></i> 使用 Java 实现 PCM 格式 转 WAV 格式并分别通过 Swing 和 Web 的形式绘制波形图
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/05/05/20170505 - IntelliJ-IDEA-For-Mac-导入导出快捷键配置/" rel="prev" title="IntelliJ IDEA For Mac 导入导出快捷键配置">
                IntelliJ IDEA For Mac 导入导出快捷键配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://wander.u.qiniudn.com/avatar.png?imageslim"
               alt="Wander.Zeng" />
          <p class="site-author-name" itemprop="name">Wander.Zeng</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/feed.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/wanderhero" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/29cd973eda7b" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  简书
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.wuliaokankan.cn/" title="无聊看看" target="_blank">无聊看看</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#生成-C-C-代码"><span class="nav-number">2.</span> <span class="nav-text">生成 C/C++ 代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#将-C-C-代码编译成动态库文件"><span class="nav-number">3.</span> <span class="nav-text">将 C/C++ 代码编译成动态库文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行-Java-程序"><span class="nav-number">4.</span> <span class="nav-text">运行 Java 程序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">5.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考"><span class="nav-number">6.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-user-circle-o"></i>
  </span>
  <span style="margin-right: 10px;" class="author" itemprop="copyrightHolder">Wander.Zeng</span>
  |<a style="margin-left: 10px;" href="http://www.miitbeian.gov.cn/">浙ICP备17021839号</a>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  








  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cyt2hHQ2h';
      var conf = '5da92ee22cc5141017c67f3c7b985f8c';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("xBKxUblXClSEpkAliADyp6c6-gzGzoHsz", "SjCMd7zwri4miARkvxbvYsfH");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.0"></script>


  

</body>
</html>
